import json
import socket
import time

from threading import Thread

from PySide2.QtCore import *
from shiboken2.shiboken2 import wrapInstance

from Tessng import *


class MySimulator(QObject, PyCustomerSimulator):
    signalRunInfo = Signal(str)
    forStopSimu = Signal()
    forReStartSimu = Signal()

    def __init__(self):
        QObject.__init__(self)
        PyCustomerSimulator.__init__(self)

        # 启动接收消息的线程
        receiveMsgThread = Thread(target=self.startUdpServer, args=())
        receiveMsgThread.start()

        # 车辆速度控制
        self.speedControl = dict()

    def startUdpServer(self, host='127.0.0.1', port=9999):
        # 创建 UDP 套接字
        udp_server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

        # 绑定套接字到指定的主机和端口
        udp_server.bind((host, port))
        print(f"UDP 服务器已启动，监听 {host}:{port}")

        while True:
            # 接收数据
            data, addr = udp_server.recvfrom(1024)  # 缓冲区大小为 1024 字节
            dataEncode = data.decode('utf-8')
            print(f"收到来自 {addr} 的消息: {dataEncode}")

            self.speedControl = json.loads(dataEncode)

            response = "消息已收到"
            udp_server.sendto(response.encode('utf-8'), addr)
            time.sleep(0.5)


    def ref_reSetSpeed(self, vehi, ref_inOutSpeed):
        # 转成字符串类型
        vehicleId = str(vehi.id())

        # 如果没收到消息，则保持1m/s的速度
        if not self.speedControl:
            ref_inOutSpeed.value = 1
            return True

        # 如果收到消息，则保持消息的速度
        if vehicleId in self.speedControl:
            speed = self.speedControl.get(vehicleId)
            # 转换为米每秒
            ref_inOutSpeed.value = int(speed/3.6)
            return True

